/**
 * 定义Ku6Flash播放器相关的交互
 * @author Akira
 */
(function(){
	var PLAYER_EVENTS = ["init","up","share","toggle"];

	function Ku6Player(cid, opts){
		//cid在页面上标识一个播放器，会影响到callSwf调用
		//flash事件参数中会把cid返回
		this.cid = cid;

		//播放器默认的属性
		this.width = 640;
		this.height = 480;
		this.playURL = "/resource/script/flash/ku6player.swf";
		this.version = "9.0.0";
		this.alt = "expressInstall.swf";

		ObjectH.mix(this, opts, true);

		/**
		 * 注册4个自定义事件
		 * init - 播放器加载完毕
		 * up - 用户点击了“顶”
		 * share - 用户点击了“分享”
		 * toggle - 用户点击了“展开”
		 */
		CustEvent.createEvents(this,PLAYER_EVENTS);

		this.init();		
	}

	Ku6Player.prototype = {
		/**
		 * 初始化播放器
		 */
		init: function(){
			var vars = {cid: this.cid};
			if(this.vid) //如果有播放
				vars.vid = this.vid;

			swfobject.embedSWF(this.playURL, this.cid, this.width, this.height, this.version, this.alt, vars, {allowScriptAccess : 'always', allowFullScreen : true}); 
			//建立播放器，播放器渲染完毕后会自动触发init事件
			//播放器的初始化是swfobject自己管理的，它会自己在Dom.ready的时候完成播放器的加载
			
			var me = this;
			this.on("init", function(){
				me._initialized = true;  //播放器加载完毕
			});
		},
		/**
		 * 调用一个flash方法，方法名+后续参数列表，如果播放器还未加载完，会等待播放器加载
		 */
		_callSwf: function(func){
			var args = Array.prototype.slice.call(arguments, 1);
			if(this._initialized){
				var swfObj = document[this.cid] || window[this.cid];
				return swfObj[func].apply(swfObj, args);	
			}else{
				var cid = this.cid;
				this.on("init", function(){ //否则等初始化完成了再加载
					var swfObj = document[cid] || window[cid];
					return swfObj[func].apply(swfObj, args);	
				});			
				return {state:"async-call"};
			}
		},
		/**
		 * 播放某个视频
		 */
		play: function(vid){
			return this._callSwf("setVid", vid);
		},
		/**
		 * 播放某个音频
		 */
		swapAudio: function(audio, url){
			return this._callSwf("audioSwap", audio, url);
		}
	}
	
	QW.provide("Ku6Player", Ku6Player);
	//window._js_PlayerHelper = new Ku6Player();

	/**
	 * 播放器的管理器，主要负责Ku6Player的创建和事件派发
	 */
	PlayerHelper = {
		create : function(cid, opts){
			var player = new Ku6Player(cid, opts);
			PlayerHelper[player.cid] = player;
			return player;
		},
		/**
		 * 将事件分发出去
		 */
		fire : function(evtType, cid, vid){
			if(evtType == "initPlayerFinished"){
				evtType = "init";
			}
			var evtArg = {cid:cid};
			if(vid){
				evtArg = {cid:cid, vid:vid};
			}
			PlayerHelper[cid].fire(evtType, evtArg);
		}
	}

	QW.provide("_js_PlayerHelper", PlayerHelper);

})();